package pl.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import pl.common.ValidationException;
import pl.model.dao.AuthorDao;
import pl.model.dao.BookDao;
import pl.model.domain.Author;
import pl.model.domain.Book;

@Controller
public class AddBookController {

    protected final Log log = LogFactory.getLog(getClass());
    protected BookDao bookDao;
    protected AuthorDao authorDao;
    
    @RequestMapping("/addBook.htm")
    public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        log.debug("AddBookController start " + bookDao + " " + authorDao);
        List authors = authorDao.getAll();
        if (request.getParameter("addBook") != null) {
            try {
                String title = request.getParameter("title");
                String tags = request.getParameter("tags");
                Author author = getAuthor(request);

                Book book = new Book(title, author, null, null, tags, null);
                log.debug("before calling persist " + book);
                bookDao.merge(book);
                request.getRequestDispatcher("listBooks.htm").forward(request, response);
                return null;
            } catch(ValidationException e){
                return new ModelAndView("addBook", "err", e.getMessage()).addObject("authors", authors);
            } catch (RuntimeException e) {
                log.debug(e.getMessage());
                return new ModelAndView("addBook", "err", e.getMessage()).addObject("authors", authors);
            }
        } else {
            return new ModelAndView("addBook").addObject("authors", authors);
        }
    }

    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }
    
    public void setAuthorDao(AuthorDao authorDao){
        this.authorDao = authorDao;
    }

    private Author getAuthor(HttpServletRequest request) {
        Integer authorId=-1;
        try {
            authorId = Integer.parseInt(request.getParameter("authorId"));
            Author author = authorDao.find(authorId);
            return author;
        } catch (NumberFormatException e) {
           throw new ValidationException("Wybierz autora");
        } catch (DataAccessException e){
           throw new ValidationException("Nie ma autora o id " + authorId);
        }
    }
}
